﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using ESoft.Core.DataAccess.Entity;
using ESoft.Core.Util.Extensions;
using ESoft.Core.Util.Helpers;
using ESoft.Core.Web.VO;
using Microsoft.EntityFrameworkCore;

namespace ESoft.Core.DataAccess.DAO.Impl
{
    public class BaseDao : IBaseDao
    {
        protected DataContext Db;


        public BaseDao(DataContext Db)
        {
            this.Db = Db;
        }

        public virtual T Find<T>(object id) where T : BaseModel, new()
        {
            return Db.Set<T>().Find(id);
        }
        public virtual async Task<T> FindAsync<T>(object id) where T : BaseModel, new()
        {
            return await Db.Set<T>().FindAsync(id);
        }

        public virtual T First<T>(Expression<Func<T, bool>> predicate) where T : BaseModel, new()
        {
            return Db.Set<T>().FirstOrDefault(predicate);
        }
        public virtual async Task<T> FirstOrDefaultAsync<T>(Expression<Func<T, bool>> predicate) where T : BaseModel, new()
        {
            return await Db.Set<T>().FirstOrDefaultAsync(predicate);
        }

        public virtual T Add<T>(T entity) where T : BaseModel, new()
        {
            PropertyInfo memberInfo = entity.GetType().GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(KeyAttribute), false).Any());

            if (memberInfo != null && memberInfo.GetValue(entity).IsNull())
            {
                entity.SetModelValue(memberInfo, StringHelper.GetId());
            }

            Db.Set<T>().Add(entity);
            Db.SaveChanges();
            return entity;
        }
        public virtual async Task<T> AddAsync<T>(T entity) where T : BaseModel, new()
        {
            PropertyInfo memberInfo = entity.GetType().GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(KeyAttribute), false).Any());

            if (memberInfo != null && memberInfo.GetValue(entity).IsNull())
            {
                entity.SetModelValue(memberInfo, StringHelper.GetId());
            }
            Db.Set<T>().Add(entity);
            await Db.SaveChangesAsync();
            return entity;
        }
        public virtual bool Update<T>(T entity) where T : BaseModel, new()
        {
            Db.Entry(entity).State = EntityState.Modified;
            Db.SaveChanges();
            return true;
        }
        public virtual async Task<T> UpdateAsync<T>(T entity) where T : BaseModel, new()
        {
            PropertyInfo memberInfo = entity.GetType().GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(KeyAttribute), false).Any());

            if (memberInfo != null && memberInfo.GetValue(entity).IsNull())
            {
                entity.SetModelValue(memberInfo, StringHelper.GetId());
            }
            Db.Set<T>().Update(entity);
            await Db.SaveChangesAsync();
            return entity;
        }
        public virtual bool Delete<T>(object id) where T : BaseModel, new()
        {
            return Delete(Find<T>(id));
        }

        public virtual bool Delete<T>(T entity) where T : BaseModel, new()
        {
            Db.Entry(entity).State = EntityState.Deleted;
            Db.SaveChanges();
            return true;
        }

        public virtual bool Delete<T>(IEnumerable<T> entities) where T : BaseModel, new()
        {
            foreach (var entity in entities)
            {
                Delete(entity);
            }
            return true;
        }

        public virtual bool Exist<T>(Expression<Func<T, bool>> predicate) where T : BaseModel, new()
        {
            return Db.Set<T>().Any(predicate);
        }

        public virtual int Count<T>(Expression<Func<T, bool>> predicate) where T : BaseModel, new()
        {
            return Db.Set<T>().Count(predicate);
        }
        public virtual async Task<int> CountAsync<T>(Expression<Func<T, bool>> predicate) where T : BaseModel, new()
        {
            return await Db.Set<T>().CountAsync(predicate);
        }
        public virtual int Sum<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, int>> selector) where T : BaseModel, new()
        {
            try
            {
                return Db.Set<T>().Where(predicate).Sum(selector);
            }
            catch
            {
                return 0;
            }
        }
        public virtual async Task<int> SumAsync<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, int>> selector) where T : BaseModel, new()
        {
            try
            {
                return await Db.Set<T>().Where(predicate).SumAsync(selector);
            }
            catch
            {
                return 0;
            }
        }
        public virtual decimal Sum<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, decimal>> selector) where T : BaseModel, new()
        {
            try
            {
                return Db.Set<T>().Where(predicate).Sum(selector);
            }
            catch
            {
                return 0;
            }
        }
        public virtual async Task<List<T>> LoadEntitiesAsync<T>() where T : BaseModel, new()
        {
            return await Db.Set<T>().ToListAsync();
        }

        public virtual IQueryable<T> LoadEntities<T>() where T : BaseModel, new()
        {
            return Db.Set<T>();
        }

        public virtual List<T> LoadEntities<T>(Expression<Func<T, bool>> predicate) where T : BaseModel, new()
        {
            return Db.Set<T>().Where(predicate).ToList();
        }
        public virtual async Task<List<T>> LoadEntitiesAsync<T>(Expression<Func<T, bool>> predicate) where T : BaseModel, new()
        {
            return await Db.Set<T>().Where(predicate).ToListAsync();
        }

        public virtual List<T> LoadPageEntities<T, TS>(PageInput page, Expression<Func<T, bool>> predicate, Expression<Func<T, TS>> keySelector, bool isAsc) where T : BaseModel, new()
        {
            var lst = Db.Set<T>().Where(predicate);
            lst = isAsc ? lst.OrderBy(keySelector) : lst.OrderByDescending(keySelector);
            return lst.Skip(page.Limit * (page.Page - 1))
                  .Take(page.Limit).ToList();
        }

        public virtual IQueryable<T> LoadPageEntities<T>(PageInput page, Expression<Func<T, bool>> predicate, SortVo sort) where T : BaseModel, new()
        {
            var lst = Db.Set<T>().Where(predicate);
            lst = sort.SortWay ? lst.OrderBy(sort.SortField) : lst.OrderByDescending(sort.SortField);

            return lst.Skip(page.Limit * (page.Page - 1))
                .Take(page.Limit);
        }
    }
}
